package service

import (
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/gogf/gf/v2/util/guid"
	"golang.org/x/net/context"
	"lot_admin_api/api"
	"lot_admin_api/internal/consts"
	"lot_admin_api/utility/response"
	"mime/multipart"
	"path"
)

type sUploadFile struct{}

var (
	insUploadFile = sUploadFile{}
)

func UploadFile() *sUploadFile {
	return &insUploadFile
}

// AliyunUploadFile 阿里云上传文件
func (s *sUploadFile) AliyunUploadFile(ctx context.Context, req *api.AliyunUploadFileReq) (res string, err error) {
	r := g.RequestFromCtx(ctx)
	uploadFile := g.RequestFromCtx(ctx).GetUploadFile("file")
	var file multipart.File
	if file, err = uploadFile.Open(); err != nil {
		response.JsonExit(r, consts.HTTPInternalServer.Code(), "没有该文件")
	}
	defer file.Close()
	endpoint := "oss-cn-beijing.aliyuncs.com"
	accessKeyId := "LTAIe00g5J5LeErR"
	accessKeySecret := "qSpuXhcfYgY7YwZCnfgx82nGerD1lL"
	bucketName := "myslfe"

	// 创建OSSClient实例。
	client, err := oss.New(endpoint, accessKeyId, accessKeySecret)
	if err != nil {
		response.JsonExit(r, consts.HTTPInternalServer.Code(), err.Error())
	}

	// 获取存储空间。
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		response.JsonExit(r, consts.HTTPInternalServer.Code(), err.Error())
	}
	fileSuffix := path.Ext(req.File.Filename)
	pathUrl := "go_lot/" + gtime.Now().Format("Y-m-d") + "/" + guid.S() + fileSuffix
	// 上传文件。
	if err = bucket.PutObject(pathUrl, file); err != nil {
		response.JsonExit(r, consts.HTTPInternalServer.Code(), err.Error())
	}
	res = "https://myslfe.oss-cn-beijing.aliyuncs.com/" + pathUrl
	return res, err
}
